function ROIstruct = fsb_ROI_mask(idat,ROIstruct)

% FSB : Calculate data for ROI area
%
% EXAMPLE:
% ROIstruct = fsb_ROI_mask(idat,ROIstruct);
%
% INPUT:
% idat: 4-D image data
% ROIstruct: ROIstruct struct containing roi and crosshair position data
%
% OUTPUT:
% ROIstruct: Updated ROIstruct struct containing a roi mask, the roi
% coordinates, and averages and standard deviations of the ROI signal
%
% CALLED BY:
% FSB.m
%
% NOTES:
% 
%
% Copyright 2010 MPI for Biological Cybernetics
% Author: Steffen Stoewer
% License:GNU GPL, no express or implied warranties
% 
% $Revision 1.0
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

dim = size(idat);

%~~~~~~~~~~~~~~~~~~~~
% Take care of matrix border issues
%~~~~~~~~~~~~~~~~~~~~

for x=1:3

    if ROIstruct.slice_n(x)-ROIstruct.roi<1
        ROIstruct.roiind(x,1) = 1;
    else
        ROIstruct.roiind(x,1) = ROIstruct.slice_n(x)-ROIstruct.roi;
    end

    if ROIstruct.slice_n(x)+ROIstruct.roi>dim(x)
        ROIstruct.roiind(x,2) = dim(x);
    else
        ROIstruct.roiind(x,2) = ROIstruct.slice_n(x)+ROIstruct.roi;
    end

end

%~~~~~~~~~~~~~~~~~~~~
% Define mask
%~~~~~~~~~~~~~~~~~~~~

ROIstruct.roimask = zeros(dim(1),dim(2),dim(3));
ROIstruct.roimask (ROIstruct.roiind(1,1):ROIstruct.roiind(1,2),...
    ROIstruct.roiind(2,1):ROIstruct.roiind(2,2),ROIstruct.roiind(3,1):ROIstruct.roiind(3,2)) = 1;
ROIstruct.roimask = logical(ROIstruct.roimask);

%~~~~~~~~~~~~~~~~~~~~
% Define ROI data
%~~~~~~~~~~~~~~~~~~~~

ROIstruct.roidata = idat(ROIstruct.roiind(1,1):ROIstruct.roiind(1,2),...
    ROIstruct.roiind(2,1):ROIstruct.roiind(2,2),ROIstruct.roiind(3,1):ROIstruct.roiind(3,2),:);
ROIstruct.roimean = fsb_meancalc(ROIstruct.roidata,4);
ROIstruct.min_hrf_avg = min(ROIstruct.roimean);
ROIstruct.max_hrf_avg = max(ROIstruct.roimean);
ROIstruct.avg_hrf_avg = mean(ROIstruct.roimean);
ROIstruct.psc_hrf_avg = (ROIstruct.max_hrf_avg-ROIstruct.min_hrf_avg)/ROIstruct.avg_hrf_avg*100;

end
